;; Fixed-Point
(define (fixed-point f first-guess)
    (define tolerance 0.000001)
    (define (close-enough? v1 v2)
        (< (abs (- v1 v2)) tolerance))
    (define (try guess)
        (let ((next (f guess)))
            (display guess)
            (newline)
            (if (close-enough? guess next)
                next
                (try next))))
    (try first-guess))

;; Newton Transform
(define (newton-transform g)
    (lambda (x)
        (- x (/ (g x) ((deriv g) x)))))

(define (deriv g)
    (lambda (x)
        (/ (- (g (+ x dx)) (g x))
           dx)))
(define dx 0.000001)

;; Newtons Method
(define (newtons-method g guess)
    (fixed-point (newton-transform g) guess))

;; SQRT
(define (sqrt x)
    (newtons-method (lambda (y) (- (square y) x))
    1.0))

(define (square x) (* x x))
(define (cube x) (* x x x))

;; Exercise 1.40
(define (cubic a b c)
    (newtons-method (lambda (x) 
                            (+ (cube x)
                            (* a (square x))
                            (* b x)
                            c))
                    1.0)) 

;; Exercise 1.41
(define (double f)
    (lambda (x) (f (f x))))
(define (inc x) (+ 1 x))

;; Exercise 1.42
(define (compose f g)
    (lambda (x) (f (g x))))

;; Exercise 1.43
;; (define (repeated f n)
;;    (if (= n 1) (lambda (x) (f x))
;;        (lambda (x) ((repeated f (- n 1)) (f x)))))
(define (repeated f n)
    (if (= n 1) (lambda (x) (f x)) 
        (lambda (x)
                ;;((compose (repeated f (- n 1)) f) x))))
                ((compose f (repeated f (- n 1))) x))))










